package com.threefish.modules.sys.controller;

import com.threefish.common.annotation.ErrorMsg;
import com.threefish.common.annotation.ResponseJsonBody;
import com.threefish.common.plugins.shiro.LoginType;
import com.threefish.common.plugins.shiro.ShiroUserToken;
import com.threefish.common.utils.StringUtils;
import com.threefish.common.vo.ResultVO;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;

/**
 * @author 黄川 huchuc@vip.qq.com
 * @date: 2018/9/10
 */
@Controller
@RequestMapping(value = "/user")
public class UserLoginController {

    @GetMapping("/login")
    public String getLogin() {
        return "login.html";
    }

    @GetMapping("/logout")
    @ResponseJsonBody
    @ErrorMsg("注销失败")
    public ResultVO logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return ResultVO.sucess("注销登录成功");
    }

    @PostMapping("/login")
    @ResponseJsonBody
    @ErrorMsg("${userName}登录失败")
    public ResultVO doLogin(@RequestParam("username") String userName, @RequestParam("password") String userPass, HttpServletRequest request) {
        ShiroUserToken token = new ShiroUserToken(userName, userPass, LoginType.web);
        token.setHost(StringUtils.getRemoteAddr(request));
        Subject subject = SecurityUtils.getSubject();
        subject.login(token);
        return ResultVO.sucess("登录成功");
    }

}
